package org.example.demo20240504.module;

import cn.hutool.core.util.ObjUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName GoodsOrderMapper
 * @Description TODO
 * @Author huarujin
 * @Date 2024/5/4 14:43
 * @Version 1.0
 */

@Service
@Slf4j
public class GoodsOrderMapper {

    private static final Map<Long, GoodsOrder> MAP = new HashMap<>();

    static {
        MAP.put(1L, GoodsOrder.builder().id(1L).name("苹果").num(100).build());
        MAP.put(2L, GoodsOrder.builder().id(2L).name("香蕉").num(100).build());
        MAP.put(3L, GoodsOrder.builder().id(3L).name("西瓜").num(100).build());
        MAP.put(4L, GoodsOrder.builder().id(4L).name("草莓").num(100).build());
    }

    public GoodsOrder get(Long id) {
        return MAP.get(id);
    }

    public void subNum(Long id, Integer num) {
        GoodsOrder order = MAP.get(id);
        if (ObjUtil.isNull(order)) {
            throw new NullPointerException("不存在的商品");
        }

        int goodsNum = order.getNum() - num;
        order.setNum(goodsNum);

        if (order.getNum() < 0) {
            throw new RuntimeException("商品数量不足");
        }

        MAP.put(id, order);
    }

}
